package config

import (
	"fmt"
	"os"
	"path/filepath"
	"slices"
	"strings"
)

func LoadCustomFyneConfig() {

	// 指定字体
	const fontsDir = `C:\Windows\Fonts`

	//fontName := `微软雅黑`
	fontName := `simhei`
	//fontName := `黑体`

	fontFilePath, err := findFontFilePath(fontName)
	// 如果没有找到文件，返回一个错误
	if err != nil {
		println(fmt.Errorf("没有找到字体: %s", fontName))
	}

	// 直接指定
	//fontFilePath := `C:\Windows\Fonts\simhei.ttf`

	// 加载字体
	//fyne.LoadResourceFromPath(fontFilePath)
	os.Setenv("FYNE_FONT", fontFilePath)

}

func findFontFilePath(fontName string) (string, error) {
	// Define common font directories for different operating systems.
	var fontDirs []string

	osHome := os.Getenv("HOME")
	switch os := os.Getenv("OS"); os {
	case "Windows_NT":
		fontDirs = []string{`C:\Windows\Fonts`}
	case "darwin": // macOS
		fontDirs = []string{"/Library/Fonts", filepath.Join(osHome, "Library/Fonts")}
	default: // Linux and other Unix-like systems
		fontDirs = []string{"/usr/share/fonts", filepath.Join(osHome, ".fonts")}
	}

	// Define the common font file extensions.
	fontExtensions := []string{".ttf", ".otf", ""}

	for _, dir := range fontDirs {

		err := filepath.WalkDir(dir, func(path string, entry os.DirEntry, err error) error {
			if err != nil {
				return err
			}
			if entry.IsDir() || !slices.Contains(fontExtensions, filepath.Ext(entry.Name())) {
				return nil
			}
			baseFileName := filepath.Base(entry.Name())
			var fileName string
			// 去除拓展名
			if strings.Contains(baseFileName, ".") {
				fileName = strings.Split(baseFileName, ".")[0]
			} else {
				fileName = baseFileName
			}
			// 找到匹配的字体名
			if strings.ToLower(fileName) == strings.ToLower(fontName) {
				return fmt.Errorf("找到字体: %s", path)
			}
			return nil
		})

		if err != nil && strings.HasPrefix(err.Error(), "找到字体") {
			fontName := strings.Split(err.Error(), " ")[1]
			return strings.TrimSpace(fontName), nil
		}
		return "", err
	}
	return "", nil
}
